﻿using System;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;

namespace EasySL.Controls
{
    public class ExDropLocation :ContentControl
    {
        public string BindProperty { get; set; }
        
        public ExDropLocation()
        {
            this.Loaded += new System.Windows.RoutedEventHandler(ExDropLocation_Loaded);
        }

        void ExDropLocation_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            FrameworkElement element = this;

            while (element != null && !(element is ExDataGrid))
                element = VisualTreeHelper.GetParent(element) as FrameworkElement;

            if (element is ExDataGrid)
            {
                var dg = element as ExDataGrid;

                foreach (ExDataGridColumn c in dg.Columns)
                {
                    if (c != null && object.Equals(c.Header, this.Content))
                    {
                        this.BindProperty = c.BindProperty;
                        dg.DropLocations.Add(this);

                        this.SetColumnHeaderBackGround(c);
                        this.SetColumnHeaderToolTip(c);
                    }
                }
            }
        }

        private void SetColumnHeaderBackGround(ExDataGridColumn c)
        {
            var backgroundElement = ((Panel)this.Parent).FindName("BackgroundRectangle");
            if (backgroundElement == null || c.BackGround == null)
                return;

            var backgroundRectangle = backgroundElement as Rectangle;
            if (backgroundRectangle.Fill is LinearGradientBrush)
                foreach (GradientStop gs in (backgroundRectangle.Fill as LinearGradientBrush).GradientStops)
                    gs.Color = c.BackGround.Color;
        }

        private void SetColumnHeaderToolTip(ExDataGridColumn c)
        {
            var parentPanel = this.Parent as Panel;

            if (parentPanel != null && c.ToolTip != null)
                ToolTipService.SetToolTip(parentPanel, c.ToolTip);
        }

        public void Show()
        {
            this.Visibility = Visibility.Visible;
        }

        public void Hide()
        {
            this.Visibility = Visibility.Collapsed;
        }

    }
}
